import {
	key
} from "@/config/index.config.js"

import {
	store
} from "../uni_modules/uni-id-pages/common/store.js"

//获取富文本内的图片url地址
export function getImgSrc(richtext, num = 3) {
	let imgList = [];
	richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
		imgList.push(capture);
	});
	imgList = imgList.slice(0, num)
	return imgList;
}

function uploadFile() {

	// 待处理
	//前端代码
	uni.chooseImage({
		count: 3,
		async success(res) {
			console.log(res);
			if (res.tempFilePaths.length > 0) {
				let filePath = res.tempFilePaths[0]
				//进行上传操作

				// promise方式
				const result = await uniCloud.uploadFile({
					filePath: filePath,
					cloudPath: 'a.jpg',
					onUploadProgress: function(progressEvent) {
						console.log(progressEvent);
						var percentCompleted = Math.round(
							(progressEvent.loaded * 100) / progressEvent.total
						);
					}
				});
			}
		}
	});

}


async function getLocation() {
	try {
		let location = await getLocationByIp()
		location = location.data
		// console.log({
		// 	location
		// });

		if (location.status == 0) {
			uni.showToast({
				title: '获取发布位置失败',
				icon: "error"
			})
			return Promise.reject('获取发布位置失败')
		}
		// 返回位置信息
		return {
			city: location.city.length ? location.city : '非法ip',
			province: location.province.length ? location.province : '非法ip'
		}
	} catch (e) {
		return Promise.reject(e.errMsg)
		// console.log('出错了', e.errMsg);
	}
}

function getLocationByIp(options) {

	return uni.request({
		url: 'https://restapi.amap.com/v3/ip',
		data: {
			key,
			...options
		}
	})
}

function getVarType(value) {
	return Object.prototype.toString.call(value).split(" ")[1].replace("]", "")
}

function throttle(timeDistance, fn) {
	let timeStamp = ''

	return function(p1, p2) {
		if (!timeStamp) {
			// console.log('执行代码');
			timeStamp = new Date().getTime()
			fn.call(this, p1, p2)
			return
		}
		if (new Date().getTime() - timeStamp <= timeDistance) {
			return `请 ${timeDistance/1000} 秒后再操作~~`
		} else {
			timeStamp = ''
			timeStamp = new Date().getTime()
			fn.call(this, p1, p2)
		}
	}
}

const getUserInfo = {
	getUserName(item) {
		return item.user_id[0].nickname || item.user_id[0].username || item.user_id[0].mobile || '未设置昵称'
	},
}

function isLogin() {
	// 暂时不用
	const em = uniCloud.getCurrentUserInfo().tokenExpired
	const tokenExpired = (em - Date.now()) < 0
	let hostUserInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
	// debugger

	const hasLogin = (Object.keys(hostUserInfo).length != 0) && !tokenExpired
	return hasLogin
}

async function loginRelease(promptText = '请登录后再操作') {
	if (!store.hasLogin) {
		uni.showToast({
			title: promptText,
			icon: "none"
		})
		return Promise.reject('未登录')
	}
	return '已经成功登录'
}

export {
	getLocationByIp,
	getVarType,
	throttle,
	getUserInfo,
	isLogin,
	loginRelease,
	getLocation,
}